package com.can.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.can.reggie.common.CustomException;
import com.can.reggie.entity.Category;
import com.can.reggie.entity.Dish;
import com.can.reggie.entity.Setmeal;
import com.can.reggie.mapper.CategoryMapper;
import com.can.reggie.service.CategoryService;
import com.can.reggie.service.DishService;
import com.can.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类,删除之前需要进行判断
     * @param id
     */
    @Override
    public void remove(Long id){
        LambdaQueryWrapper<Dish> dish_lqw = new LambdaQueryWrapper<>();
        //添加查询条件
        dish_lqw.eq(Dish::getCategoryId,id);
        //查询当前分类是否关联了菜品，如果已经关联，抛出一个业务异常
        int count = dishService.count(dish_lqw);
        if (count>0){
            //KEY: 为什么这里抛异常也能捕获得到,定义的全局异常处理ControllerAdvice(annotations = {RestController.class, Controller.class})
            //KEY: 中没有@service注解呀!!!!
            //已经关联菜品,抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品,不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmeal_lqw = new LambdaQueryWrapper<>();
        //添加查询条件
        setmeal_lqw.eq(Setmeal::getCategoryId,id);
        //查询当前分类是否关联了套餐，如果已经关联，抛出一个业务异常
        int count1 = setmealService.count(setmeal_lqw);
        if (count1>0){
            //已经关联套餐,抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }
        //正常删除分类
        super.removeById(id);
    }
}
